package com.sky.happygos.YiPush;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sky.happygos.R;
import com.sky.happygos.common.Constants;
import com.sky.happygos.ui.activity.MainA_;

import org.androidannotations.annotations.EService;

/**
 * Created by qqqqqqq on 2017/4/20.
 */

public class PushService extends Service{
    public boolean isRuning = false;
    public boolean pause = true;

    private final int PID = android.os.Process.myPid();

    public TcpClient tcpClient;

    String userid;
    String host;
    int port;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(PID, NotificationManagerU.getLongNotification(this));


        MyReceiver myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_OPEN);
        filter.addAction(Constants.ACTION_CLOSE);
        registerReceiver(myReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.v("yipush","isRuning:"+isRuning+" intent:"+intent);
        if(!isRuning && intent != null) {

            String host = intent.getStringExtra("EXTRA_PUSH_HOST");
            int port = intent.getIntExtra("EXTRA_PUSH_PORT",0);
            String userid = intent.getStringExtra("EXTRA_PUSH_USERID");
            Log.v("yipush","host:"+host+" port:"+port+" userid:"+userid);
            if(host != null && userid != null){
                this.host = host;
                this.port = port;
                this.userid = userid;
            }
            createTcpClient();
            tcpClient.start();
        }
        Log.v("yipush","=====================service onStart==============================");
        return super.onStartCommand(intent, START_FLAG_REDELIVERY, startId);
    }

    public void createTcpClient(){
        tcpClient = new TcpClient(host,port,new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.arg1 == 666){
                    Toast.makeText(PushService.this,"YiPush连接成功",Toast.LENGTH_SHORT).show();
                }else {
                    if(!pause) {
                        Msg m = ProtoJsonU.to(msg);
                        NotificationManagerU.show(PushService.this, m);
                        Log.v("yipush", "receive => " + m.data);
                    }
                }

            }
        });
        tcpClient.setUserid(userid);
        isRuning = true;
    }

    public void start(){
        pause = false;
    }

    public void stop(){
        pause = true;
    }



    private static void startServiceAfterClosed(Context context, int delayed) {
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayed * 1000, getOperation(context));
    }

    public static void cancelAutoStartService(Context context) {
        AlarmManager alarm = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(getOperation(context));
    }

    private static PendingIntent getOperation(Context context) {
        Intent intent = new Intent(context, PushService.class);
        PendingIntent operation = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return operation;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        startServiceAfterClosed(this,5);
    }


    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("MyReceiver", intent.getAction());
            try {
                if (Constants.ACTION_OPEN.equals(intent.getAction())) {
                    PushService.this.start();
                } else if (Constants.ACTION_CLOSE.equals(intent.getAction())) {
                    PushService.this.stop();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
